<template>
  <div class="addRoles">
    <div class="container">
      <el-form
        class="roleForm"
        ref="ruleFormRef"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <div class="title">
          <div class="icon"></div>
          {{ $t("system.RoleInformation") }}
        </div>
        <el-form-item :label="$t('system.RoleName')" prop="roleName">
          <el-input
            :disabled="openType === 'detail'"
            clearable
            v-model="roleForm.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('system.Remark')">
          <el-input
            :disabled="openType === 'detail'"
            clearable
            v-model="roleForm.remark"
            placeholder="请输入备注说明"
            :rows="3"
            type="textarea"
          ></el-input>
        </el-form-item>

        <div class="title">
          <div class="icon"></div>
          {{ $t("system.RightsManagement") }}
        </div>
        <el-tree
          :data="treeData"
          ref="treeRef"
          node-key="id"
          show-checkbox
          :disabled="true"
          class="table-tree"
          default-expand-all
          empty-text="加载中，请稍候"
        />
      </el-form>
    </div>
    <div class="save-button save-button1" v-if="openType === 'detail'">
      <el-button class="btn delete" @click="cancelSub(ruleFormRef)">
        {{ openType !== "detail" ? $t("common.cancel") : $t("common.close") }}
      </el-button>
    </div>
    <div class="save-button" v-else>
      <el-button class="btn delete" @click="cancelSub(ruleFormRef)">
        {{ openType !== "detail" ? $t("common.cancel") : $t("common.close") }}
      </el-button>
      <el-button class="btn save" @click="submit(ruleFormRef)">
        {{ $t("common.confirm") }}
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "AddRoles",
  beforeRouteEnter(to, from, next) {
    const { openType } = to.query;
    if (openType === "edit") to.meta.title = "编辑角色";
    if (openType === "detail") to.meta.title = "角色详情";
    if (openType === "add") to.meta.title = "新增角色";
    next();
  },
};
</script>

<script setup>
import { onMounted, reactive, ref, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import {
  roleMenuTreeselect,
  treeselect as menuTreeselect,
} from "@/api/system/menu";
import {
  addRole,
  changeRoleStatus,
  dataScope,
  delRole,
  getRole,
  listRole,
  updateRole,
  deptTreeSelect,
} from "@/api/system/role";
import { useRoute, useRouter } from "vue-router";

const router = useRouter();
const route = useRoute();
// 权限数据
const treeData = ref([]);
const treeRef = ref();
const ruleFormRef = ref();
const roleId = ref();
const openType = ref();
const defaultProps = ref({
  children: "children",
  label: "label",
  disabled: "disabled",
});

let roleForm = reactive({
  roleName: null,
  menuIds: [],
  remark: "",
});
const rules = reactive({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});

/**
 * @获取权限数据
 * */
const getMenuTreeselect = async () => {
  const { data } = await menuTreeselect();
  console.log(data);
  if (openType.value === "detail") {
    data.forEach((item) => {
      item.disabled = true;
      if (item.children) {
        deepEach(item.children);
      }
    });
    treeData.value = data;
  } else treeData.value = data;
};

/**
 * @子节点处理
 * */
function deepEach(arr) {
  arr.forEach((item) => {
    item.disabled = true;
    if (item.children) {
      deepEach(item.children); // 递归
    }
  });
}

/**
 * @获取选中的权限ID
 * */
const getCheckedKey = () => {
  let checkedKeys = treeRef.value.getCheckedKeys(false);
  let halfcheckedKeys = treeRef.value.getHalfCheckedKeys(false);
  return [...checkedKeys, ...halfcheckedKeys];
};

/**
 * @角色权限校验
 * */
function validateMenuIds() {
  if (getCheckedKey().length > 0) return true;
  else {
    ElMessage.error("请设置角色权限！");
    return false;
  }
}

/**
 * @提交表单
 * */
const submit = async (formEl) => {
  if (!formEl) return;
  if (!validateMenuIds()) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = null;

      if (roleId.value) {
        res = await updateRole({
          ...roleForm,
          roleId: roleId.value,
          menuIds: getCheckedKey(),
        });
      } else {
        res = await addRole({
          ...roleForm,
          // roleKey: "csess",
          roleSort: 13,
          status: "0",
          menuIds: getCheckedKey(),
        });
      }
      if (res.code === 200) {
        ElMessage.success(res.msg);
        router.push("/system/role");
      } else {
        ElMessage.error(res.msg);
      }
    } else {
      ElMessage.error("提交数据验证未通过，请检查填写内容！");
    }
  });
};

const cancelSub = async (formEl) => {
  formEl.resetFields();
  router.push("/system/role");
};
// ------------------------------------------------------------  生命周期    ------------------------------------------------------

onBeforeMount(async () => {
  openType.value = route.query.openType;
  roleId.value = route.query.roleId;
  getMenuTreeselect();
});

onMounted(async () => {
  if (roleId.value) {
    const { data } = await getRole(roleId.value);
    roleForm.roleName = data.roleName;
    roleForm.roleKey = data.roleKey;
    roleForm.roleSort = data.roleSort;
    roleForm.status = data.status;
    const res = await roleMenuTreeselect(roleId.value);
    let checkedKeys = res.checkedKeys;
    checkedKeys.forEach((v) => {
      nextTick(() => {
        treeRef.value.setChecked(v, true, false);
      });
    });
  }
});
</script>

<style lang="scss">
.table-tree {
  .el-tree-node {
    margin-bottom: 20px;
    width: 90%;
    border: 1px solid rgba(232, 232, 232, 1);

    .el-tree-node__content {
      padding-left: 20px !important;
      width: 100%;
      height: 50px;
      opacity: 1;
      background: rgba(244, 244, 244, 1);

      .el-tree-node__expand-icon {
        display: none;
      }
    }

    .el-tree-node__children {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      background: rgba(255, 255, 255, 1);

      .el-tree-node {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 0;
        width: 100%;
        background: rgba(255, 255, 255, 1);
        border: none;
        border-bottom: 1px solid rgba(232, 232, 232, 1);

        .el-tree-node__content {
          width: 200px;
          height: 50px;
          opacity: 1;
          background: rgba(255, 255, 255, 1);
          border-right: 1px solid rgba(232, 232, 232, 1);
        }

        .el-tree-node__children {
          flex: 1;
          display: flex !important;
          flex-direction: row;
          justify-content: flex-start;
          align-items: center;

          .el-tree-node {
            flex: 1;
            border: none;
            border-right: 1px solid rgba(232, 232, 232, 1);
            .el-tree-node__content {
              border: none;
            }
            .el-tree-node__children {
              width: 0;
            }
          }
        }
      }
    }
  }
}
</style>

<style scoped lang="scss">
.addRoles {
  width: 100%;
  height: 100%;
  // box-sizing: border-box;
  position: relative;

  .container {
    position: relative;
    width: calc(100% - 40px);
    height: 92%;
    margin: 0 20px 20px;
    border-radius: 10px;
    background: white;
    overflow-y: scroll; /* 显示垂直滚动条 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* Internet Explorer and Edge */

    .title {
      display: flex;
      align-items: center;
      margin: 30px 20px;
      font-size: 16px;
      font-weight: 600;

      .icon {
        margin-right: 12px;
        width: 16px;
        height: 16px;
        background: url("@/assets/images/titleIcon.png");
      }
    }

    .roleForm {
      margin-bottom: 30px;

      .el-input,
      .el-textarea {
        width: 456px;
      }
    }
  }

  .save-button {
    position: absolute;
    right: 20px;
    top: -45px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 160px;
    height: 40px;
  }

  .save-button {
    width: auto;
    height: 40px;
  }

  .btn {
    width: 81px;
    height: 32px;
    line-height: 32px;
    text-align: center;
    border-radius: 4px;
    color: #fff;
    background: rgba(43, 193, 123, 1);
    cursor: pointer;
    &:hover {
      background: rgba(43, 193, 123, 0.85);
    }
  }

  .btn.delete {
    color: rgba(102, 102, 102, 1);
    background: #fff;
    border: 1px solid rgba(220, 223, 230, 1);
    &:hover {
      background: rgba(0, 0, 0, 0.05);
    }
  }
}
</style>
